package com.lucher.mes.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lucher.mes.common.HttpTools;
import com.lucher.mes.common.Tools;
import com.lucher.mes.dao.DepotrackinfoMapper;
import com.lucher.mes.dao.ToolplateMapper;
import com.lucher.mes.dao.ToolinoutMapper;
import com.lucher.mes.dao.ToolplateinfoMapper;
import com.lucher.mes.dao.OperatorMapper;
import com.lucher.mes.dao.PrisonerMapper;
import com.lucher.mes.dao.TooldepotMapper;
import com.lucher.mes.po.Depotrackinfo;
import com.lucher.mes.po.Material;
import com.lucher.mes.po.Toolplate;
import com.lucher.mes.po.Toolinout;
import com.lucher.mes.po.Toolplate;
import com.lucher.mes.po.Toolplateinfo;
import com.lucher.mes.po.Workline;
import com.lucher.mes.po.Operator;
import com.lucher.mes.po.Prisoner;
import com.lucher.mes.po.Tooldepot;
import com.lucher.mes.service.ICoderuleService;
import com.lucher.mes.service.ISystemparaService;

/**
 * 用户控制层
 */
@Controller
@Scope("prototype")
@RequestMapping("/tooluse")
@Transactional
public class TooluseController extends BaseController {

	@Autowired
	private ToolplateMapper toolplateDao;
	@Autowired
	private ICoderuleService coderuleService;
	@Autowired
	private ToolinoutMapper toolinoutDao;
	@Autowired
	private OperatorMapper operatorDao;
	@Autowired
	private DepotrackinfoMapper depotrackinfoDao;
	@Autowired
	private PrisonerMapper prisonerDao;
	@Autowired
	private ToolplateinfoMapper toolplateinfoDao;
	@Autowired
	private TooldepotMapper tooluseDao;
	@Autowired
	private ISystemparaService systemparaService;
	
	/*
     * 特殊的instance变量
     * 注：零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：
     * 生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码。
     */
    private static byte[] lock = new byte[0];
	
	/**
	 * 查询工具领用主界面
	 */
	@RequestMapping(value = "/findByList")
	public String findByList(Toolplate form, Model model) {
		model.addAttribute("totalOutnum",toolplateDao.findTotalOutnum(new Toolplate()));
		return "tooluse/findTooldepotList";
	}
	
	/**
	 * 查询工具领用
	 */
	@RequestMapping(value = "/addTooluseInit")
	public String addTooluseInit(Toolplate form, Model model) {
		//model.addAttribute("totalOutnum",toolplateDao.findTotalOutnum(new Toolplate()));
		return "tooluse/addTooluse";
	}
	
	
	
	/**
	 * 查询工具领用主界面
	 */
	@RequestMapping(value = "/findToolunreturnList")
	public String findToolunreturnList(Toolplate form, Model model) {
		model.addAttribute("totalOutnum",toolplateDao.findTotalOutnum(new Toolplate()));
		return "tooluse/findToolunreturnList";
	}
	
	/**
	 * 查询材料库存Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findToolunreturnListJson")
	public Map<String, Object> findToolunreturnListJson(Toolinout form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		result.put("code", "0");
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
		
		form.setInoutstatus("领用");
		
		Integer total = toolinoutDao.findByCount(form);
		List<Toolinout> list = toolinoutDao.findByListForPage(form);
		for (Toolinout toolinout : list) {
			
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			objectMap.put("id", toolinout.getId());
			objectMap.put("toolcode", toolinout.getToolcode());
			objectMap.put("toolname", toolinout.getToolname());
			objectMap.put("model", toolinout.getModel());
			objectMap.put("description", toolinout.getDescription());
			objectMap.put("operatorcode", toolinout.getOperatorcode());
			objectMap.put("inoutamount", toolinout.getInoutamount());
			objectMap.put("usetime", StringUtils.isEmpty(toolinout.getUsetime())?"":Tools.getStr(toolinout.getUsetime()).substring(0, 19));
			objectMap.put("useinfo", toolinout.getUseinfo());
			objectMap.put("inoutercode", toolinout.getInoutercode());
			objectMap.put("inoutername", toolinout.getInoutername());
			objectMap.put("inoutstatus", toolinout.getInoutstatus());
			objectMap.put("depotrackcode", toolinout.getDepotrackcode());
			objectMap.put("returntime", StringUtils.isEmpty(toolinout.getReturntime())?"":Tools.getStr(toolinout.getReturntime()).substring(0, 19));
			objectMap.put("returninfo", toolinout.getReturninfo());
			
			objectlist.add(objectMap);
		}
		
		result.put("count", total);//页面总数
		result.put("data", objectlist);
		return result;
	}
	
	/**
	 * 查询工具领用主界面
	 */
	@RequestMapping(value = "/findTooluseList")
	public String findTooluseList(Toolplate form, Model model) {
		model.addAttribute("totalOutnum",toolplateDao.findTotalOutnum(new Toolplate()));
		return "tooluse/findTooluseList";
	}
	
	/**
	 * 查询工具库存Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findTooluseListJson")
	public Map<String, Object> findTooluseListJson(Toolplate form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
//		
//		Integer total = toolplateDao.findByCount(form);
//		List<Toolplate> list = toolplateDao.findByList(form);
		
        //工具借用服务器URL
		String send_tool_url = systemparaService.findSystemParaByCodeStr("send_tool_url");
		JSONObject jsonParam = new JSONObject();
		jsonParam.put("method", "tools_borrow");
		String data = HttpTools.sedPostAsRaw(jsonParam, send_tool_url);
		if(StringUtils.isNotBlank(data)){ //不为空
			//返回的是一个[{}]格式的字符串时:                               
	        JSONObject jsonObject = new JSONObject(data);   
	        String response_code = jsonObject.getString("response_code");
	        if("0".equals(response_code)){//表示成功
	        	String prisoner = jsonObject.getString("prisoner");
		        JSONArray toolsArray = jsonObject.getJSONArray("tools");
		        //有质量问题的产品,必须要重新分包
 				if(toolsArray != null && toolsArray.length() > 0){
 					//循环有问题的产品包数
 					for (int j = 0; j < toolsArray.length(); j++) {
 						    HashMap<String, Object> objectMap = new HashMap<String, Object>();
							JSONObject toolinfo = toolsArray.getJSONObject(j);
							String tools_name = Tools.getStr(toolinfo.getString("tools_name"));
							int tools_number = toolinfo.getInt("tools_number");
							objectMap.put("prisonercode", prisoner);
							objectMap.put("toolname", tools_name);
							objectMap.put("inoutamount", tools_number);
							objectlist.add(objectMap);
 					}
 				}
	        }
		}
		result.put("code", "0");
		//result.put("count", total);//页面总数
		result.put("data", objectlist);
		return result;
	}
	
	/**
	 * 保存工具领用
	 * @throws Exception 
	 */
	@RequestMapping(value = "/saveTooluser")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@Transactional
	public  Map<String,Object>  saveTooluser(Toolplate form,Toolinout toolinout){
		Operator operator = (Operator)getSession().getAttribute("Operator");
		String currentTime =  Tools.getCurrentTime();
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		//加锁
		synchronized(lock) {
			String data = toolinout.getTooluseJSON();
			if(StringUtils.isNotBlank(data)){ //不为空
				JSONArray toolsArray = new JSONArray(data);   
				if(toolsArray != null && toolsArray.length() > 0){
					//循环工具领用数组，进行验证判断
					for (int j = 0; j < toolsArray.length(); j++) {
						JSONObject toolinfo = toolsArray.getJSONObject(j);
						String prisonercode = Tools.getStr(toolinfo.getString("prisonercode"));
						String toolname = Tools.getStr(toolinfo.getString("toolname"));
						int inoutamount = toolinfo.getInt("inoutamount");
						//查找该库存中该犯人编号存不存在
						Prisoner query = new Prisoner();
						query.setPrisonercode(prisonercode);
						Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(query);
						if(prisoner == null){
							responseJson.put("flag", "0"); //操作失败
							responseJson.put("msg", "操作失败，人员编号不存在！");
							return responseJson;
						}
						//查找该库存中该工具编号存不存在
						Toolplate toolplate  = toolplateDao.findByToolname(toolname);
						if(toolplate == null){
							responseJson.put("flag", "0"); //操作失败
							responseJson.put("msg", "操作失败，"+toolname +" 库存中不存在！");
							return responseJson;
						}
						//查找该库存中该工具库存数量够不够
						//领用量不能大于仓库剩余数
						if(toolplate.getLeftnum()-inoutamount < 0){
							responseJson.put("flag", "0"); //操作失败
							responseJson.put("msg", "操作失败，" + toolname + " 领用数量超过了库存量！");
							return responseJson;
						}
					}
					//循环工具领用数组，进行业务操作
					for (int j = 0; j < toolsArray.length(); j++) {
						JSONObject toolinfo = toolsArray.getJSONObject(j);
						String prisonercode = Tools.getStr(toolinfo.getString("prisonercode"));
						String toolname = Tools.getStr(toolinfo.getString("toolname"));
						int inoutamount = toolinfo.getInt("inoutamount");
						//查找该库存中该犯人编号存不存在
						Prisoner query = new Prisoner();
						query.setPrisonercode(prisonercode);
						Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(query);
						//查找该库存中该工具编号存不存在
						Toolplate toolplate  = toolplateDao.findByToolname(toolname);
						//已有库存量
						int leftnum = toolplate.getLeftnum();
						//更新剩余量
						toolplate.setLeftnum(leftnum-inoutamount);
						//更新借出量
						toolplate.setOutnum(toolplate.getOutnum() + inoutamount);
						toolplateDao.updateByPrimaryKeySelective(toolplate);
						
						//出入库记录
						Toolinout toolinoutRecord = new Toolinout();
						//增加工具领用记录
						toolinoutRecord.setToolcode(toolplate.getToolcode());
						toolinoutRecord.setToolname(toolplate.getToolname());
						toolinoutRecord.setOperatorcode(operator.getLoginname());
						toolinoutRecord.setInoutamount(inoutamount);
						toolinoutRecord.setUsetime(currentTime);
						toolinoutRecord.setInoutstatus("领用");
						toolinoutRecord.setDepotrackcode(toolplate.getToolplatecode());
						toolinoutRecord.setInoutercode(prisonercode);
						toolinoutRecord.setInoutername(prisoner.getPrisonername());
						toolinoutDao.insertSelective(toolinoutRecord);
					}

					responseJson.put("flag", "1"); 
					responseJson.put("msg", "操作成功");
					return responseJson;
					
				}else{
					responseJson.put("flag", "0"); //操作失败
					responseJson.put("msg", "操作失败，没有工具借用数据！");
					return responseJson;
				}
			}else{
				responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，没有工具借用！");
				return responseJson;
			}
		}
	}
	
	/**
	 * 查询工具归还主界面
	 */
	@RequestMapping(value = "/findToolreturnList")
	public String findToolreturnList(Toolplate form, Model model) {
		model.addAttribute("totalOutnum",toolplateDao.findTotalOutnum(new Toolplate()));
		return "tooluse/findToolreturnList";
	}
	
	/**
	 * 查询工具归还Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findToolreturnListJson")
	public Map<String, Object> findToolreturnListJson(Toolplate form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
//		
//		Integer total = toolplateDao.findByCount(form);
//		List<Toolplate> list = toolplateDao.findByList(form);
		
        //工具借用服务器URL
		String send_tool_url = systemparaService.findSystemParaByCodeStr("send_tool_url");
		JSONObject jsonParam = new JSONObject();
		jsonParam.put("method", "tools_return");
		String data = HttpTools.sedPostAsRaw(jsonParam, send_tool_url);
		if(StringUtils.isNotBlank(data)){ //不为空
			//返回的是一个[{}]格式的字符串时:                               
	        JSONObject jsonObject = new JSONObject(data);   
	        String response_code = jsonObject.getString("response_code");
	        if("0".equals(response_code)){//表示成功
	        	String prisoner = jsonObject.getString("prisoner");
		        JSONArray toolsArray = jsonObject.getJSONArray("tools");
		        //有质量问题的产品,必须要重新分包
 				if(toolsArray != null && toolsArray.length() > 0){
 					//循环有问题的产品包数
 					for (int j = 0; j < toolsArray.length(); j++) {
 						    HashMap<String, Object> objectMap = new HashMap<String, Object>();
							JSONObject toolinfo = toolsArray.getJSONObject(j);
							String tools_name = Tools.getStr(toolinfo.getString("tools_name"));
							int tools_number = toolinfo.getInt("tools_number");
							objectMap.put("prisonercode", prisoner);
							objectMap.put("toolname", tools_name);
							objectMap.put("inoutamount", tools_number);
							objectlist.add(objectMap);
 					}
 				}
	        }
		}
		result.put("code", "0");
		//result.put("count", total);//页面总数
		result.put("data", objectlist);
		return result;
	}
	
	
	/**
	 * 保存工具领用
	 * @throws Exception 
	 */
	@RequestMapping(value = "/saveToolreturn")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@Transactional
	public  Map<String,Object>  saveToolreturn(Toolplate form,Toolinout toolinout){
		Operator operator = (Operator)getSession().getAttribute("Operator");
		
		String currentTime =  Tools.getCurrentTime();
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		//加锁
		synchronized(lock) {
			String data = toolinout.getTooluseJSON();
			if(StringUtils.isNotBlank(data)){ //不为空
				JSONArray toolsArray = new JSONArray(data);   
				if(toolsArray != null && toolsArray.length() > 0){
					//循环工具领用数组，进行验证判断
					for (int j = 0; j < toolsArray.length(); j++) {
						JSONObject toolinfo = toolsArray.getJSONObject(j);
						String prisonercode = Tools.getStr(toolinfo.getString("prisonercode"));
						String toolname = Tools.getStr(toolinfo.getString("toolname"));
						int inoutamount = toolinfo.getInt("inoutamount");
						//查找该库存中该犯人编号存不存在
						Prisoner query = new Prisoner();
						query.setPrisonercode(prisonercode);
						Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(query);
						if(prisoner == null){
							responseJson.put("flag", "0"); //操作失败
							responseJson.put("msg", "操作失败，人员编号不存在！");
							return responseJson;
						}
						//查找该库存中该工具编号存不存在
						Toolplate toolplate  = toolplateDao.findByToolname(toolname);
						if(toolplate == null){
							responseJson.put("flag", "0"); //操作失败
							responseJson.put("msg", "操作失败，"+toolname +" 库存中不存在！");
							return responseJson;
						}
						//查找该库存中该工具库存数量够不够
						//领用量不能大于仓库剩余数
						if(toolplate.getOutnum()-inoutamount < 0){
							responseJson.put("flag", "0"); //操作失败
							responseJson.put("msg", "操作失败，" + toolname + " 归还数量超过了借用总数量！");
							return responseJson;
						}
					}
					//循环工具领用数组，进行业务操作
					for (int j = 0; j < toolsArray.length(); j++) {
						JSONObject toolinfo = toolsArray.getJSONObject(j);
						String prisonercode = Tools.getStr(toolinfo.getString("prisonercode"));
						String toolname = Tools.getStr(toolinfo.getString("toolname"));
						int inoutamount = toolinfo.getInt("inoutamount");
						//查找该库存中该犯人编号存不存在
						Prisoner query = new Prisoner();
						query.setPrisonercode(prisonercode);
						Prisoner prisoner = prisonerDao.findPrisonerByPrisonercode(query);
						//查找该库存中该工具编号存不存在
						Toolplate toolplate  = toolplateDao.findByToolname(toolname);
						//更新剩余量
						toolplate.setLeftnum(toolplate.getLeftnum() + inoutamount);
						//更新借出量
						toolplate.setOutnum(toolplate.getOutnum()-inoutamount);
						
						toolplateDao.updateByPrimaryKeySelective(toolplate);
						
						//出入库记录
						Toolinout toolinoutRecord = new Toolinout();
						//增加工具领用记录
						toolinoutRecord.setToolcode(toolplate.getToolcode());
						toolinoutRecord.setToolname(toolplate.getToolname());
						toolinoutRecord.setOperatorcode(operator.getLoginname());
						toolinoutRecord.setInoutamount(inoutamount);
						toolinoutRecord.setUsetime(currentTime);
						toolinoutRecord.setReturntime(currentTime);
						toolinoutRecord.setInoutstatus("归还");
						toolinoutRecord.setDepotrackcode(toolplate.getToolplatecode());
						toolinoutRecord.setInoutercode(prisonercode);
						toolinoutRecord.setInoutername(prisoner.getPrisonername());
						toolinoutDao.insertSelective(toolinoutRecord);
					}

					responseJson.put("flag", "1"); 
					responseJson.put("msg", "操作成功");
					return responseJson;
					
				}else{
					responseJson.put("flag", "0"); //操作失败
					responseJson.put("msg", "操作失败，没有工具借用数据！");
					return responseJson;
				}
			}else{
				responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，没有工具借用！");
				return responseJson;
			}
		}
	}
}
